<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{{ url_for('static', filename='index.css') }}">
    <title>Student Website</title>
</head>

<body>
<div class="main-container">
    <div class="content">
        <div class="navbar">
            <span class="title"><a href="/" style="text-decoration: none; color: black">Back To Main Page</a></span>
        </div>
        <a onclick="window.history.go(-1)">Back</a>
        <div>
            <div class="content-block">
                <h2 class="section-title"><span id="homework_title">Homework</span></h2>
                <p class="section-content" id="homework_requirements">Requirements...</p>
            </div>

            <div class="content-block">
                <p class="section-title">ClassName</p>
                <p class="section-content" id="class_name">ClassName...</p>
            </div>

            <div class="content-block">
                <p class="section-title">Start time</p>
                <p class="section-content" id="begin_time">Start time...</p>
            </div>

            <div class="content-block">
                <p class="section-title">End time</p>
                <p class="section-content" id="over_time">End time...</p>
            </div>
        </div>

        <div class="card" id="submission_card">
            <h2>
                Submission
            </h2>
            <p>
                Enter or upload the job
            </p>
            <div id="editor" contenteditable="true"></div>
            <!-- 添加文件上传输入框 -->
            <input type="file" id="fileInput" accept=".docx, .pdf" style="margin-top: 10px;">
            <br>
            <button class="button" style="margin-top: 10px;" onclick="submit()">Submit</button>
        </div>
    </div>
</div>
<div class="sidebar">
    <div class="card" id="submission_card">
        <h2>Submission History</h2>
        <ul id="file_list"></ul>
        <div id="homework_sub_history">
            <p>No more.</p>
        </div>
    </div>
</div>
</body>

<script>
    let username;
    const homework_title_span = document.getElementById("homework_title");
    const homework_requirements = document.getElementById("homework_requirements");
    const class_name_span = document.getElementById("class_name");
    const begin_time_span = document.getElementById("begin_time");
    const over_time_span = document.getElementById("over_time");
    const submission_card = document.getElementById("submission_card");

    function getUrlParam(urlKey) {
        const url = new URL(window.location.href)
        var reg = new RegExp('[\?\&]' + urlKey + '=([^\&]*)(\&?)', 'i')
        var r = url.search.match(reg)
        return r ? r[1] : ''
    }

    const classname = getUrlParam("classname");
    const homeworkname = getUrlParam("homeworkname");

    fetch('/api/get_user_name')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(data => {
            username = data;

            fetch(`/api/users/${username}`, {
                method: 'GET',
            })
                .then(response => {
                    if (response.ok) {
                        return response.json();
                    } else {
                        throw new Error('Failed to get class');
                    }
                })
                .then(userinfo_data => {
                    if (userinfo_data.data[2] != "0") {
                        submission_card.style.display = "none";
                    } else {
                        const uptype = document.querySelectorAll('[type="uptype"]');
                        uptype.forEach(element => {
                            element.parentNode.removeChild(element);
                        });
                    }

                    fetch(`/api/homeworks?homeworkname=${homeworkname}&classname=${classname}`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then(data => {
                            console.log('Success:', data);

                            homework_title_span.innerHTML = data.data[1];
                            class_name_span.innerHTML = data.data[0];
                            homework_requirements.innerHTML = data.data[2];
                            begin_time_span.innerHTML = data.data[3];
                            over_time_span.innerHTML = data.data[4];

                            fetch(`/api/sub_homeworks?homeworkname=${homeworkname}&classname=${classname}`)
                                .then(response => {
                                    if (!response.ok) {
                                        throw new Error('Network response was not ok');
                                    }
                                    return response.json();
                                })
                                .then(data => {
                                    console.log('Success:', data);

                                    const homeworkSubHistory = document.getElementById('homework_sub_history');
                                    homeworkSubHistory.innerHTML = '';
                                    data.data.forEach(item => {
                                        const listItem = document.createElement('div');
                                        listItem.innerHTML = `
                                        <hr>
                                        <p style="line-height: 5px;">Time: ${item[4]}</p>
                                        <p style="line-height: 5px;">StudentName: ${item[2]}</p>
                                        <p>Ratings<br><div style="padding: 5px; background-color: #3d3d3d10;">${item[5] == "" ? "<span style='color: red'>Unscored</span>" : (item[5] == "A+" ? `<span style='color: green'>A+</span>` : item[5])}</p></div>
                                        <p>Evaluation<br><div style="padding: 20px; background-color: #3d3d3d10;">${item[6] == "" ? "<span style='color: red'>No comment</span>" : item[6]}</p></div>
                                        <br>
                                        <div type="uptype">
                                            <select id="ratingsSelect${item[2]}" class="input">
                                                <option value="A+">A+</option>
                                                <option value="A-">A-</option>
                                                <option value="B+">B+</option>
                                                <option value="B-">B-</option>
                                                <option value="C+">C+</option>
                                                <option value="C-">C-</option>
                                                <option value="fail">fail</option>
                                            </select>
                                            <br>
                                            <textarea id="evaluationTextarea${item[2]}" rows="4" cols="50" class="input"></textarea>
                                            <br>
                                            <button class="button" onclick="correction('${item[2]}')">Correction</button>
                                        <div>
                                `;
                                        homeworkSubHistory.appendChild(listItem);
                                    });
                                    fetch(`/api/users/${username}`, {
                                        method: 'GET',
                                    })
                                        .then(response => {
                                            if (response.ok) {
                                                return response.json();
                                            } else {
                                                throw new Error('Failed to get class');
                                            }
                                        })
                                        .then(userinfo_data => {
                                            if (userinfo_data.data[2] == "0") {
                                                const uptype = document.querySelectorAll('[type="uptype"]');
                                                uptype.forEach(element => {
                                                    element.parentNode.removeChild(element);
                                                });
                                            }
                                        })
                                        .catch(error => {
                                            console.error('Error:', error);
                                        });
                                })
                                .catch(error => {
                                    console.error('Error:', error);
                                });
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                })
                .catch(error => {
                    console.error('There has been a problem with your fetch operation:', error);
                });
        })
        .catch(error => {
            console.error('There was a problem with the fetch operation:', error);
        });

    fetch('/api/list_files')
        .then(response => response.json())
        .then(files => {
            const fileListElement = document.getElementById('file_list');
            // 循环文件列表，创建列表项和下载链接
            files.forEach(file => {
                const listItem = document.createElement('li');
                const downloadLink = document.createElement('a');
                downloadLink.href = file.download_link;
                downloadLink.textContent = file.file_name;
                downloadLink.setAttribute('download', file.file_name);
                listItem.appendChild(downloadLink);
                fileListElement.appendChild(listItem);
            });
        })
        .catch(error => {
            console.error('获取文件列表失败:', error);
        });

    function getFile() {
        const fileName = document.getElementById('get_file').value;
        fetch(`/download/${encodeURIComponent(fileName)}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.blob();
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName; // 使用用户输入的文件名
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            })
            .catch(e => console.error(e));
    }

    function truncateString(str) {
        if (str.length > 15) {
            return str.slice(0, 15) + '...';
        } else {
            return str;
        }
    }

    function boldText() {
        document.execCommand('bold');
    }

    function italicText() {
        document.execCommand('italic');
    }

    document.getElementById('colorPicker').addEventListener('input', function () {
        document.execCommand('foreColor', false, this.value);
    });

    function submit() {
        const value = document.getElementById('editor').innerHTML;
        const studentname = username;
        const fileInput = document.getElementById('fileInput');
        const file = fileInput.files[0];

        const formData = new FormData();
        formData.append('classname', classname);
        formData.append('homeworkname', homeworkname);
        formData.append('value', value);
        formData.append('studentname', studentname);
        formData.append('file', file, file.name);

        fetch('/api/sub_homeworks', {
            method: 'POST',
            body: formData
        })
            .then(response => {
                if (response.status == 400) {
                    alert("You've already submitted");
                    location.reload();
                } else if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log('Success:', data);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

    function correction(studentname) {
        var ratings = document.getElementById(`ratingsSelect${studentname}`).value;
        var evaluation = document.getElementById(`evaluationTextarea${studentname}`).value;

        fetch('/api/scores', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                "homework_name": homeworkname,
                "class_name": classname,
                "student_name": studentname,
                "ratings": ratings,
                "evaluation": evaluation
            })
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log('Success:', data);
                window.location.reload();
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }
</script>

<style>


    body {
        display: flex; /* 将body设为Flex容器 */
        height: 100vh; /* 确保body充满全屏高度，以便侧栏能沿高度扩展 */
        margin: 0; /* 清除默认边距 */
    }

    .main-container {
        flex-grow: 1; /* 主内容区域自适应填充剩余空间 */
        padding: 20px; /* 为内容区域添加内边距 */
    }

    .sidebar {
        width: 300px; /* 设置侧栏宽度 */
        margin-left: 20px; /* 侧栏与主内容之间的间隙 */
    }

    .content-block {
        /* 添加边框以区分每个块 */
        border: 5px solid #ccc;
        /* 内边距使内容与边框有间隔 */
        padding: 15px;
        /* 外边距提供块之间的空间 */
        margin-bottom: 15px;
        /* 圆角增加视觉友好性（可选） */
        border-radius: 5px;
    }

    .section-title {
        font-size: 20px;
        color: #000;
        margin-bottom: 10px;
    }

    .section-content {
        font-size: 18px;
        color: #333;
        line-height: 1.5;
    }

    .card {
        background-color: #dddddd;
        margin: 20px 5%;
        padding: 15px 30px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        border-radius: 15px;
    }

</style>
</html>